namespace ProjectFootball.Models.Entities.Membership.Configuration
{
    using System.Data.Entity.Migrations;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using ProjectFootball.Models.Entities.Membership;

    // Add-Migration -Name PfMembership -ConfigurationTypeName PfMembershipConfiguration
    // Update-Database -ConfigurationTypeName PfMembershipConfiguration

    internal sealed class PfMembershipConfiguration : DbMigrationsConfiguration<PfMembershipDbContext>
    {
        public PfMembershipConfiguration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(PfMembershipDbContext context)
        {
            AddUserToRole("admin@projectfootball.co.uk", "aaaaaa", "Admin");
            AddUserToRole("user1@projectfootball.co.uk", "111111", string.Empty);
            AddUserToRole("user2@projectfootball.co.uk", "111111", string.Empty);

            context.SaveChanges();
        }

        private void AddUserToRole(string userName, string password, string roleName)
        {
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new PfMembershipDbContext()));
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new PfMembershipDbContext()));
            userManager.UserValidator = new UserValidator<ApplicationUser>(userManager) { AllowOnlyAlphanumericUserNames = false };

            userManager.PasswordValidator = new MinimumLengthValidator(6);

            var user = new ApplicationUser() { UserName = userName };

            userManager.Create(user, password);

            if (roleName.Length > 0)
            {
                if (!roleManager.RoleExists(roleName))
                    roleManager.Create(new IdentityRole(roleName));

                userManager.AddToRole(user.Id, roleName);
            }
        }
    }
}
